package lazy.util;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageUtils {
	private enum LogicGate {
		AND, OR, XOR, NOT, COMPLEMENT;
		int compute(int mask, int rgb) {
			int i = -1;
			switch(this) {
				case AND:
					i = mask&rgb;
					break;
				case OR:
					i = mask|rgb;
				case XOR:
					i = mask^rgb;
			}
			return i;
		}
	}
	private static BufferedImage mixMask(LogicGate gate, int mask, BufferedImage image) {
		BufferedImage bi = null;
		if(image!=null) {
			int w = image.getWidth();
			int h = image.getHeight();
			bi = new BufferedImage(w, h, image.getType());
			//
			try {
				for(int x=0;x<w;x++) {
					for(int y=0;y<h;y++) {
						bi.setRGB(x, y, gate.compute(mask, image.getRGB(x, y)));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bi;
	}
	public static BufferedImage toGrayscale(BufferedImage image) {
		BufferedImage bi = null;
		if(image!=null) {
			int w = image.getWidth();
			int h = image.getHeight();
			bi = new BufferedImage(w, h, image.getType());
			//
			try {
				for(int x=0;x<w;x++) {
					for(int y=0;y<h;y++) {
						int rgb = image.getRGB(x, y)&0x00FFFFFF;
						float[] hsb = Color.RGBtoHSB((rgb&0xFF0000)>>16, (rgb&0x00FF00)>>8, (rgb&0x0000FF)>>0, null);
						bi.setRGB(x, y, Color.HSBtoRGB(hsb[0], 0, hsb[2]));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return bi;
	}
	public static BufferedImage toInvert(BufferedImage image) {
		return mixMask(LogicGate.XOR ,0xFFFFFF, image);
	}

		
	public static void main(String[] args) {
		try {
			ImageIO.write(ImageUtils.toGrayscale(ImageIO.read(new java.io.File("c:/IMG_3528.jpg"))),"jpg",new java.io.File("c:/IMG_35282.jpg"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
